package Day01;

/**
 * 归并排序模板
 * 分界点：数组下标的中间值
 */
public class MergeSort {

    public static void mergeSort(int[] arr, int l, int r) {
        // 判断边界
        if (l >= r) {
            return;
        }
        int mid = l + (r - l) / 2;
        mergeSort(arr, l, mid);
        mergeSort(arr, mid + 1, r);
        int k = 0;
        int i = l;
        int j = mid + 1;
        int[] tmp = new int[1000010];
        while (i <= mid && j <= r) {
            if (arr[i] < arr[j]) {
                tmp[k++] = arr[i++];
            } else {
                tmp[k++] = arr[j++];
            }
        }
        while (i <= mid) {
            tmp[k++] = arr[i++];
        }
        while (j <= r) {
            tmp[k++] = arr[j++];
        }
        for (i = l, j = 0; i <= r; i++, j++) {
            arr[i] = tmp[j];
        }
    }


    public static void main(String[] args) {

        int[] arr = new int[]{4, 3, 1, 8, 6};
        mergeSort(arr, 0, 4);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + ",");
        }
    }
}
